package com.yljk.yljkproject.rnmodule;



import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.alsk.rn.kit.bridge.impl.net.KitNetworkModule;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableMap;
import com.yilijk.base.AppBase;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.oss.UploadOssUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.ToastUtils;
import com.yljk.servicemanager.constants.ConfigApi;
import com.yljk.servicemanager.view.CustomeDialog;
import com.yljk.yljkproject.utils.ReactUtils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;


/**
 * 原生提供给RN使用的网络方法
 * Android provide react-native net function
 */

public class RNNetworkModule extends KitNetworkModule {


    private CustomeDialog customeDialog;


    /**
     * 网络请求
     *
     * @param reactContext
     * @param domin 域名
     * @param methodName 请求字段
     * @param type 请求类型
     * @param params 接受数据
     * @param promise 回调
     */

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (customeDialog.isShowing()) {
                    customeDialog.dismiss();
                }
            }
        }
    };

    @Override
    public void requestNet(@NotNull ReactContext reactContext, @NotNull String domin, @NotNull String methodName, @NotNull String type, @NotNull boolean isLoading, @NotNull ReadableMap params, @NotNull Promise promise) {

        /**
         * log 打印接受数据
         */
        CommonUtils.loginfo("Android accept domim:" + domin);
        CommonUtils.loginfo("Android accept domim:" + methodName);
        CommonUtils.loginfo("Android accept type:" + type);
        CommonUtils.loginfo("Android accept params:" + params);
        CommonUtils.loginfo("Android accept params:" + isLoading);
//        if (isLoading){
//            customeDialog = new CustomeDialog.Builder(reactContext.getCurrentActivity()).create();
//            customeDialog.show();
//            handler.sendEmptyMessage(1);
//        }
        /**
         * 判断POST/GET请求
         *
         */
        if (ConfigApi.Open.isAndroidDomin) {
            if (!methodName.startsWith("http") && !methodName.startsWith("https")) {
                if (methodName.startsWith("/")) {
                    domin = HttpUtils.getUrl();
                } else {
                    domin = HttpUtils.getUrl() + "/";
                }
            }
        }
        boolean isOss = true;
        if (params.hasKey("isOss")) {
            isOss = params.getBoolean("isOss");
        }
        String requestJson = "";
        JSONObject paramsJSON = ReactUtils.INSTANCE.getPramasJSONObject(params.toString());
        RequestParams requestParams = null;
        try {
            if (paramsJSON.has("NativeMap")) {
                requestJson = paramsJSON.getString("NativeMap");
            } else {
                requestJson = paramsJSON.toString();
            }
            requestParams = new RequestParams(requestJson);
            if (reactContext != null && reactContext.getCurrentActivity() != null) {
                Activity context = reactContext.getCurrentActivity();
                Intent intent = context.getIntent();
                String module = intent.getStringExtra("intent_key_plugin_id");
//                modulePage.append("_").append(intent.getStringExtra("intent_key_module_id"));
                String modulePage = intent.getStringExtra("intent_key_component_name");
                if (!TextUtils.isEmpty(module)) {
                    requestParams.put("module", module);
                }
                if (!TextUtils.isEmpty(modulePage)) {
                    requestParams.put("modulePage", modulePage);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        switch (type) {
            case "POST": {
                HttpUtils.post(methodName, requestParams, new HttpCallBack<String>() {
                    @Override
                    public void onSuccess(String result, int code) {
                        promise.resolve(result);
                        dialog_cancel();
                    }

                    @Override
                    public void onFailure(String failureMsg, int statusCode) {
                        promise.resolve(failureMsg);
                        dialog_cancel();
                    }
                });
                break;
            }
            case "GET": {
                HttpUtils.get(methodName, requestParams, new HttpCallBack<String>() {
                    @Override
                    public void onSuccess(String result, int code) {
                        promise.resolve(result);
                        dialog_cancel();
                    }

                    @Override
                    public void onFailure(String failureMsg, int statusCode) {
                        promise.resolve(failureMsg);
                        dialog_cancel();
                    }
                });
                break;
            }
            case "UPLOAD": {
                String filePath = null;
                if (params.hasKey("filePath")) {
                    try {
                        filePath = params.getString("filePath");
                    } catch (Exception e) {
                        ALog.e("RNNetWorkModule", e.getMessage());
                    }
                }
                if (TextUtils.isEmpty(filePath)){
                    RequestParams exceptionParams = new RequestParams();
                    exceptionParams.put("result", false);
                    exceptionParams.put("status", 0);
                    exceptionParams.put("data", "");
                    exceptionParams.put("msg", "请选择标准图片进行上传");
                    promise.resolve(exceptionParams.toString());
                    return;
                }
                String uri2Path = null;
                File file = null;
                if (filePath.charAt(0) != '/') {
                    uri2Path = CommonUtils.getModuleCommonUtils().Uri2Path(AppBase.getApplication(), filePath);
                } else {
                    uri2Path = filePath;
                }
                file = new File(uri2Path);
                if (isOss) {
                    //如果上传成功的路径
                    String ossPath = UploadOssUtils.getInstance().getData().getStartWith() + "android/doctor/image/" + file.getName().replace("_", "");
                    HttpUtils.uploadFile2Oss(file, new HttpCallBack<String>() {
                        @Override
                        public void onSuccess(String result, int code) {
                            RequestParams upLoadResult = new RequestParams();
                            upLoadResult.put("result", true);
                            upLoadResult.put("status", 200);
                            upLoadResult.put("data", "https://imageserver.yilijk.com/" + ossPath);
                            promise.resolve(upLoadResult.toString());
                            dialog_cancel();
                        }

                        @Override
                        public void onFailure(String failureMsg, int statusCode) {
                            UploadOssUtils.getInstance().init();
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("result", false);
                                jsonObject.put("msg", failureMsg);
                                jsonObject.put("message", failureMsg);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            promise.resolve(jsonObject.toString());
                            dialog_cancel();
                        }
                    });
                } else {
                    HttpUtils.uploadFile(domin + methodName, new RequestParams(), filePath, new HttpCallBack<String>() {
                        @Override
                        public void onSuccess(String result, int code) {
                            promise.resolve(result);
                            dialog_cancel();
                        }

                        @Override
                        public void onFailure(String failureMsg, int statusCode) {
                            promise.resolve(failureMsg);
                            dialog_cancel();
                        }
                    });
                }

                break;
            }
            case "UPLOADFILE": {
                String filePath = null;
                if (params.hasKey("filePath")) {
                    try {
                        filePath = params.getString("filePath");
                    } catch (Exception e) {
                        ALog.e("RNNetWorkModule", e.getMessage());
                    }
                }
                if (TextUtils.isEmpty(filePath)){
                    RequestParams exceptionParams = new RequestParams();
                    exceptionParams.put("result", false);
                    exceptionParams.put("status", 0);
                    exceptionParams.put("data", "");
                    exceptionParams.put("msg", "请选择标准图片进行上传");
                    promise.resolve(exceptionParams.toString());
                    return;
                }
                File file = null;
                file = new File(filePath);
                if (!file.exists()) {
                    ToastUtils.showShort("文件不存在");
                    return;
                }

                if (isOss) {
                    String s = UploadOssUtils.getInstance().getData().getStartWith() + "android/doctor/file/" + file.getName().replace("_", "");
                    HttpUtils.uploadAmr2Oss(file, new HttpCallBack<String>() {
                        @Override
                        public void onSuccess(String result, int code) {
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("result", true);
                                jsonObject.put("status", 200);
                                jsonObject.put("data", "https://imageserver.yilijk.com/" + s);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            promise.resolve(jsonObject.toString());
                            dialog_cancel();
                        }

                        @Override
                        public void onFailure(String failureMsg, int statusCode) {
                            UploadOssUtils.getInstance().init();
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("result", true);
                                jsonObject.put("msg", failureMsg);
                                jsonObject.put("message", failureMsg);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            promise.resolve(jsonObject.toString());
                            dialog_cancel();
                        }
                    });
                } else {
                    HttpUtils.uploadAmr(domin + methodName, file, new HttpCallBack<String>() {
                        @Override
                        public void onSuccess(String result, int code) {
                            promise.resolve(result);
                            dialog_cancel();
                        }

                        @Override
                        public void onFailure(String failureMsg, int statusCode) {
                            promise.resolve(failureMsg);
                            dialog_cancel();
                        }
                    });
                }


//            String filePath = params.getString("filePath");

                break;
            }
        }
    }

    private void dialog_cancel() {
        if (customeDialog != null && customeDialog.isShowing()) {
            customeDialog.dismiss();
            customeDialog = null;
            handler.removeMessages(1);
        }
    }

}